package cn.xawl.gulimall.product.web;

import cn.xawl.gulimall.product.entity.CategoryEntity;
import cn.xawl.gulimall.product.service.CategoryService;
import cn.xawl.gulimall.product.vo.Catalog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lh
 * @create 2020-10-20 13:00
 *
 * index页面
 *
 **/
@Controller
public class IndexController {

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping({"/", "/index.html"})
    public String index(Model model) {
        List<CategoryEntity> firstLevel = categoryService.firstLevelCategories();

        model.addAttribute("categories", firstLevel);

        return "index";
    }

    @GetMapping("/index/catalog.json")
    @ResponseBody
    public Map<String, List<Catalog2Vo>> catalogJson() {

        Map<String, List<Catalog2Vo>> catalogJson = categoryService.buildCatalog2Vo();

        return catalogJson;
    }

    @GetMapping("/write")
    @ResponseBody
    public String write() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        String uuid = UUID.randomUUID().toString();
        try{
            try {
                TimeUnit.SECONDS.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            redisTemplate.opsForValue().set("test", uuid);
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            writeLock.unlock();
        }
        return uuid;
    }


    @GetMapping("/read")
    @ResponseBody
    public String read() {
        RReadWriteLock readWriteLock = redissonClient.getReadWriteLock("rw-lock");
        RLock readLock = readWriteLock.readLock();
        readLock.lock();
        String uuid = "";
        try{
            uuid = redisTemplate.opsForValue().get("test");
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            readLock.unlock();
        }
        return uuid;
    }

}
